<?php

/**
 * Administrative class
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to the MIT License, available
 * at http://www.opensource.org/licenses/mit-license.html
 *
 * @author     Jayson Schmidt <jayson@888mobileapps.com>
 * @copyright  2013 888MobileApps
 * @license    http://www.opensource.org/licenses/mit-license.html
 */

class Admin extends DB_Connect {
	
	private $_saltLength = 7;
	
	/*
	 * Stores or creates a DB object and sets salt length
	 *
	 * @param obj $db a database object
	 * @param int $saltLength length for password hash
	 */
	
	public function __construct($db=NULL, $saltLength=NULL) {
		parent::__construct($db);
		
		if(is_int($saltLength))
			$this->_saltLength = $salthLength;
	}
	
	/*
	 * Checks login credentials for a valid user
	 * 
	 * @return mixed TRUE on success, message on error
	 */
	 
	 public function processLoginForm() {
	 	
		/*
		 * Fails if proper action was not submitted
		 */
		if($_POST['action'] != 'user_login') 
			return "Invalid action supploed for processLoginForm.";
			
		$uname = htmlentities($_POST['uname'], ENT_QUOTES);
		$pword = htmlentities($_POST['pword'], ENT_QUOTES);
		
		$sql = "SELECT
					*
				FROM 
					`user`
				WHERE
					`user_name` = :uname
				LIMIT 1";
		
		try {
		
			$stmt = $this->db->prepare($sql);
			$stmt->bindParam(':uname', $uname, PDO::PARAM_STR);
			$stmt->execute();
			$user = array_shift($stmt->fetchAll());
			$stmt->closeCursor();
		
		}catch(Exception $e) {
			
			die($e->getMessage());
		
		}
		
		if(!isset($user))
			return "Username or password is invalid.";
			
		$hash = $this->_getSaltedHash($pword, $user['password']);
		
		if($user['password'] == $hash) {
			$_SESSION['user'] = array(
						'id' => $user['pid'],
						'name' => $user['user_name']
						);
						
			return TRUE;
		
		}else {
			return "Username or password is invalid";
		}
	 
	 }
	 
	 /*
	  * Logs out the user
	  * @return mixed TRUE on success, message on failure
	  */
	  
	  public function processLogout() {
	  	
		if($_POST['action'] != 'user_logout')
			return "Invalid action supplied for processLogout";
			
		/*
		 * Removes the user array from the current session
		 */
		session_destroy();
		return TRUE;
	  
	  
	  }
	 
	 /*
	  * Generates a salted hash of a supplied string
	  *
	  * @param string $string to be hashed
	  * @param string $salt extract the hash from here
	  * @return string the salted hash
	  */
	  private function _getSaltedHash($string, $salt=NULL) {
	  	
		/*
		 * Generate salt if none is passed
		 */
		if($salt == NULL)
		 	$salt = substr(md5(time()),0,$this->_saltLength);
		else
			$salt = substr($salt, 0, $this->_saltLength);
			
		/*
		 * Add the salt to the hash and return it
		 */	
		return $salt.sha1($salt.$string); 
	  
	  }
	  
	  public function testSaltedHash($string, $salt=NULL) {
	  	return $this->_getSaltedHash($string, $salt);
	  }
	  

}

?>
